package org.samith.web.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.samith.web.helper.AuthenticatedUserSession;

public final class AuthenticationFilter implements Filter {

	private Object authenticationStatus;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filter) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession();
		authenticationStatus = session.getAttribute("authenticatedUser");
		boolean loginFormSubmitted = httpRequest.getRequestURI().equals(
				"/ejbApp/login")
				&& httpRequest.getMethod().equals("POST");

		boolean isInSignupProcess = httpRequest.getRequestURI().equals(
				"/ejbApp/signup")
				&& (httpRequest.getMethod().equals("GET") || httpRequest
						.getMethod().equals("POST"));

		boolean isVerifyAccountProcess = httpRequest.getRequestURI().equals(
				"/ejbApp/verifyAccount")
				&& (httpRequest.getMethod().equals("GET") || httpRequest
						.getMethod().equals("POST"));

		boolean isForgotPasswordProcess = httpRequest.getRequestURI().equals(
				"/ejbApp/forgotPassword")
				&& (httpRequest.getMethod().equals("GET") || httpRequest
						.getMethod().equals("POST"));
		
		boolean isForgotPasswordResetProcess = httpRequest.getRequestURI().equals(
		"/ejbApp/forgotPasswordReset")
		&& (httpRequest.getMethod().equals("GET") || httpRequest
				.getMethod().equals("POST"));

		boolean isWebServicesRequest = httpRequest.getRequestURI().indexOf(
				"/ejbApp/WS/services/") != -1;

		if (httpRequest.getRequestURI().equals("/ejbApp/")
				|| loginFormSubmitted || isWebServicesRequest
				|| isForgotPasswordProcess || isInSignupProcess
				|| isVerifyAccountProcess || isForgotPasswordResetProcess) {
			filter.doFilter(request, response);
		} else {
			if (isAllowedToView(httpRequest, httpResponse)) {
				filter.doFilter(request, response);
			} else {
				RequestDispatcher rd = request
						.getRequestDispatcher("/WelcomeUsers/login.jsp");
				rd.forward(request, response);
			}
		}
	}

	@Override
	public void init(FilterConfig arg) throws ServletException {
	}

	private boolean isAllowedToView(HttpServletRequest httpRequest,
			HttpServletResponse httpResponse) {
		if (authenticationStatus != null) {
			AuthenticatedUserSession userSession = (AuthenticatedUserSession) authenticationStatus;
			if (userSession.isAuthenticated()) {
				return true;
			}
		}
		return false;
	}
}
